import 'dart:ui';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/models/business_entity.dart';
import 'package:yurun_smartmerchants/models/getperson_information_entity.dart';
import 'package:yurun_smartmerchants/models/personinformation_response_entity.dart';
import 'package:yurun_smartmerchants/models/upload_image_response_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/net/NetUtil.dart';
import 'package:yurun_smartmerchants/page/notification_webview.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/utils/base64.dart';
import 'package:yurun_smartmerchants/utils/dialog_utils.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';

import '../global.dart';

class PersonalInformationImprovement extends StatefulWidget {
  int type; //等于1代表主页面跳转过来的

  PersonalInformationImprovement({Key key, this.type});

  @override
  _PersonalInformationImprovementState createState() =>
      _PersonalInformationImprovementState();
}

class _PersonalInformationImprovementState
    extends State<PersonalInformationImprovement> {
  ///真实姓名
  TextEditingController _relNameeditingController = TextEditingController();

  ///备案类型 临时商户2 固定商户1
  int recordType = 0;
  List<BusinessResponseType> type;
  List<BusinessResponseTypechild> currentchildrenType = new List();

  ///身份证号码
  TextEditingController _carNumbereditingController = TextEditingController();

  ///身份证照片
  UploadImageResponseEntity cardentity, backcardentity;

  bool isSelectButton = true;

  var marketValue;

  String selectMarketName = '';
  int selectMarketId = 0;
  final _picker = ImagePicker();
  File _image;
  File _imageBackCard;

  GetpersonInformationEntity informationEntity;

  @override
  void initState() {
    super.initState();
    cardentity = UploadImageResponseEntity();
    cardentity.content = List<UploadImageResponseContent>();
    backcardentity = UploadImageResponseEntity();
    backcardentity.content = List<UploadImageResponseContent>();
    getRecordInformation();
    getBusiNessType();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          leading: new IconButton(
              icon: new Icon(Icons.arrow_back, color: Colors.black),
              onPressed: () => Navigator.of(context).pop()),
          centerTitle: true,
          title: Text(
            '完善个人备案',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
        ),
        body: SingleChildScrollView(
          child: Material(
            child: Column(
              children: <Widget>[
                firstSection(),
                secondSection(),
                bottomSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget firstSection() {
    return Container(
      margin: EdgeInsets.only(left: 0, right: 0),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          relNameCell(),
          recordTypeCell(),
          businessTypeCell(),
        ],
      ),
    );
  }

  Widget relNameCell() {
    return Container(
      height: 58,
      decoration: UnderlineTabIndicator(
          borderSide: BorderSide(width: 0.5, color: Colours.mine_bg),
          insets: EdgeInsets.zero),
      child: Stack(
        children: <Widget>[
          Container(
            //灰色块
            width: MediaQuery.of(context).size.width,
            height: 12,
            color: Colours.mine_bg,
          ),
          Positioned(
            left: 15,
            top: 23,
            width: 80,
            height: 25,
            child: Text(
              '真实姓名',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
          ),
          Positioned(
            left: 88,
            top: 27,
            width: 1,
            height: 21,
            child: Text(
              '*',
              style: TextStyle(fontSize: 18, color: Colors.red),
            ),
          ),
          Positioned(
            left: 120,
            right: 20,
            top: 32,
            height: 25,
            child: TextField(
              textAlign: TextAlign.right,
              controller: _relNameeditingController,
              decoration: InputDecoration(
                hintText: "请输入真实姓名",
                hintStyle: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  color: Colours.information_placeholder,
                ),
                border: InputBorder.none,
              ),
              style: TextStyle(
                fontSize: ScreenUtil().setSp(28),
              ),
              inputFormatters: <TextInputFormatter>[
                LengthLimitingTextInputFormatter(10) //限制长度
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget recordTypeCell() {
    return Container(
      height: 46,
      decoration: UnderlineTabIndicator(
          borderSide: BorderSide(width: 0.5, color: Colours.mine_bg),
          insets: EdgeInsets.zero),
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 15,
            top: 11,
            width: 80,
            height: 25,
            child: Text(
              '备案类型',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
          ),
          Positioned(
            left: 88,
            top: 15,
            width: 1,
            height: 21,
            child: Text(
              '*',
              style: TextStyle(fontSize: 18, color: Colors.red),
            ),
          ),
          Positioned(
            top: 12,
            right: 20,
            height: 21,
            child: Row(
              children: <Widget>[
                Radio(
                  value: 0,
                  activeColor: Colors.red,
                  onChanged: (value) {
                    setState(() {
                      if (this.recordType != value) {
                        selectMarketName = '';
                        selectMarketId = 0;
                      }
                      this.recordType = value;
                    });
                  },
                  groupValue: this.recordType,
                ),
                Text(
                  "临时商户",
                  style: TextStyle(
                    color: this.recordType == 0 ? Colors.red : Colors.black,
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                Radio(
                  value: 1,
                  activeColor: Colors.red,
                  onChanged: (value) {
                    setState(() {
                      if (this.recordType != value) {
                        selectMarketName = '';
                        selectMarketId = 0;
                      }
                      this.recordType = value;
                    });
                  },
                  groupValue: this.recordType,
                ),
                Text(
                  "固定商户",
                  style: TextStyle(
                    color: this.recordType == 1 ? Colors.red : Colors.black,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget businessTypeCell() {
    return Container(
      height: 46,
      decoration: UnderlineTabIndicator(
          borderSide: BorderSide(width: 0.5, color: Colours.mine_bg),
          insets: EdgeInsets.zero),
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 15,
            top: 11,
            width: 80,
            height: 25,
            child: Text(
              '经营类型',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
          ),
          Positioned(
            left: 88,
            top: 15,
            width: 1,
            height: 21,
            child: Text(
              '*',
              style: TextStyle(fontSize: 18, color: Colors.red),
            ),
          ),
          Positioned(
            top: 12,
            width: 120,
            right: 10,
            height: 21,
            child: DropdownButton(
              items: getListData(),
              onChanged: _handleMarketType,
              hint: new Text(
                  selectMarketName.length == 0 ? '市场商户' : selectMarketName),
              style: new TextStyle(color: Colors.red),
              isDense: true,
              iconSize: 25,
            ),
          ),
        ],
      ),
    );
  }

  Widget secondSection() {
    return Container(
      margin: EdgeInsets.only(left: 0, right: 0),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          cardNumberCell(),
          cardPhotoCell(),
        ],
      ),
    );
  }

  Widget cardNumberCell() {
    return Container(
      height: 58,
      decoration: UnderlineTabIndicator(
          borderSide: BorderSide(width: 0.5, color: Colours.mine_bg),
          insets: EdgeInsets.zero),
      child: Stack(
        children: <Widget>[
          Container(
            //灰色块
            width: MediaQuery.of(context).size.width,
            height: 12,
            color: Colours.mine_bg,
          ),
          Positioned(
            left: 15,
            top: 23,
            width: 100,
            height: 25,
            child: Text(
              '身份证号码',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
          ),
          Positioned(
            left: 120,
            right: 20,
            top: 32,
            height: 25,
            child: TextField(
              textAlign: TextAlign.right,
              controller: _carNumbereditingController,
              decoration: InputDecoration(
                hintText: "输入身份证号码",
                hintStyle: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  color: Colours.information_placeholder,
                ),
                border: InputBorder.none,
              ),
              style: TextStyle(
                fontSize: ScreenUtil().setSp(28),
              ),
              inputFormatters: <TextInputFormatter>[
                LengthLimitingTextInputFormatter(30) //限制长度
              ],
              onChanged: (value) {
                setState(() {});
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget cardPhotoCell() {
    return Container(
      height: 180,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 15,
            top: 11,
            width: 100,
            height: 25,
            child: Row(
              children: <Widget>[
                Text(
                  '身份证照片',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 15,
            right: 15,
            top: 22,
            height: 165,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return _showNomalWid(context);
                            });
                      },
                      child: Container(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            getImage(),
                          ],
                        ),
                      ),
                    )),
                Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return _showImageTip(context);
                            });
                      },
                      child: Container(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            getBackCardImage(),
                          ],
                        ),
                      ),
                    )),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget bottomSection() {
    return Container(
      margin: EdgeInsets.only(left: 0, right: 0),
      child: Column(
        children: <Widget>[
          agreenMentCell(),
        ],
      ),
    );
  }

  Widget agreenMentCell() {
    return Container(
      height: 298,
      decoration: UnderlineTabIndicator(
          borderSide: BorderSide(width: 0.5, color: Colours.mine_bg),
          insets: EdgeInsets.zero),
      child: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: <Widget>[
          Positioned(
            left: 20,
            right: 20,
            top: 208,
            height: 25,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    setState(() {
                      this.isSelectButton = !this.isSelectButton;
                    });
                  },
                  child: Image.asset(
                    isSelectButton
                        ? 'images/mine_selectimage.png'
                        : 'images/mine_unselect.png',
                    fit: BoxFit.fill,
                    width: AppSize.height(35),
                    height: AppSize.width(35),
                  ),
                ),
                Text(
                  '已阅读告知书并同意',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 16.0,
                  ),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).push(new MaterialPageRoute(
                      builder: (BuildContext context) => WebViewBrowser(
                        url: 'http://www.epfresh.com',
                        title: '告知书',
                      ),
                    ));
                  },
                  child: Text(
                    '《告知书》',
                    style: TextStyle(
                      color: Colors.red,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 20,
            right: 20,
            top: 243,
            height: 44,
            child: RaisedButton(
              child: Text(
                '保 存',
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              color: Colors.red,
              textColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              onPressed: _save,
            ),
          ),
        ],
      ),
    );
  }

  void getBusiNessType() {
    ApiInterface.getBusinessType().then((data) {
      BusinessResponse businessResponse =
          JsonConvert.fromJsonAsT<BusinessResponse>(data);
      setState(() {
        this.type = businessResponse.type;
      });
    });
  }

  ///获取备案信息
  void getRecordInformation() {
    String consumerId = Global.prefs.getString(Global.consumer_id).toString();
    if(consumerId != null && consumerId.length > 0) {
//    LoadingUtil.showLoading(context, tip: "获取信息中，请稍后。。。");
      ApiInterface.getPersonInfo(3).then((data) {
      informationEntity = GetpersonInformationEntity().fromJson(data);

      setState(() {
        if(informationEntity.businessType.name != null && informationEntity.businessType.name.length > 0) {
          _relNameeditingController.text = informationEntity.businessType.name;
        }
        if(informationEntity.type != null && informationEntity.type != 0) {
          this.recordType = informationEntity.type;
        }
        if(informationEntity.businessTypeName != null && informationEntity.businessTypeName.length > 0 && informationEntity.businessTypeId != null && informationEntity.businessTypeId > 0) {
          this.selectMarketName = informationEntity.businessTypeName;
          this.selectMarketId = informationEntity.businessTypeId;
        }
        if(informationEntity.certification.idCardNo != null && informationEntity.certification.idCardNo.length > 0) {
          _carNumbereditingController.text = informationEntity.certification.idCardNo;
        }
        if(informationEntity.certification.credentials[0].filePathi != null && informationEntity.certification.credentials[0].filePathi.length > 0) {
         UploadImageResponseContent firstContent = UploadImageResponseContent();
         firstContent.path = informationEntity.certification.credentials[0].filePathi;
         firstContent.id = informationEntity.certification.credentials[0].fileIdi;
         cardentity.content.add(firstContent);
        }
        if(informationEntity.certification.credentials[0].filePathii != null && informationEntity.certification.credentials[0].filePathii.length > 0) {
          UploadImageResponseContent backCardContent = UploadImageResponseContent();
          backCardContent.path = informationEntity.certification.credentials[0].filePathii;
          backCardContent.id = informationEntity.certification.credentials[0].fileIdii;
          backcardentity.content.add(backCardContent);
        }
      });
      });
    }
  }


  void _handleMarketType(item) {
    setState(() {
      for (var i = 0; i < this.currentchildrenType.length; i++) {
        if (this.currentchildrenType[i].id == item) {
          selectMarketName = this.currentchildrenType[i].name;
          selectMarketId = this.currentchildrenType[i].id;
          break;
        }
      }
    });
  }

  bool isCardId(String cardId) {
    if (cardId.length != 18) {
      return false; // 位数不够
    }
    // 身份证号码正则
    RegExp postalCode = new RegExp(
        r'^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|[Xx])$');
    // 通过验证，说明格式正确，但仍需计算准确性
    if (!postalCode.hasMatch(cardId)) {
      return false;
    }
    //将前17位加权因子保存在数组里
    final List idCardList = [
      "7",
      "9",
      "10",
      "5",
      "8",
      "4",
      "2",
      "1",
      "6",
      "3",
      "7",
      "9",
      "10",
      "5",
      "8",
      "4",
      "2"
    ];
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    final List idCardYArray = [
      '1',
      '0',
      '10',
      '9',
      '8',
      '7',
      '6',
      '5',
      '4',
      '3',
      '2'
    ];
    // 前17位各自乖以加权因子后的总和
    int idCardWiSum = 0;

    for (int i = 0; i < 17; i++) {
      int subStrIndex = int.parse(cardId.substring(i, i + 1));
      int idCardWiIndex = int.parse(idCardList[i]);
      idCardWiSum += subStrIndex * idCardWiIndex;
    }
    // 计算出校验码所在数组的位置
    int idCardMod = idCardWiSum % 11;
    // 得到最后一位号码
    String idCardLast = cardId.substring(17, 18);
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if (idCardMod == 2) {
      if (idCardLast != 'x' && idCardLast != 'X') {
        return false;
      }
    } else {
      //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
      if (idCardLast != idCardYArray[idCardMod]) {
        return false;
      }
    }
    return true;
  }

  List<DropdownMenuItem> getListData() {
    List<DropdownMenuItem> item = new List();
    if (this.type != null && this.type.length > 1) {
      this.currentchildrenType = this.type[this.recordType].children;
      for (var i = 0; i < this.currentchildrenType.length; i++) {
        DropdownMenuItem dropdownMenuItem = new DropdownMenuItem(
          child: new Text(this.currentchildrenType[i].name),
          value: this.currentchildrenType[i].id,
        );
        item.add(dropdownMenuItem);
      }
    }
    return item;
  }

//选择照片
  Widget _showNomalWid(BuildContext context) {
    return new Container(
        height: AppSize.height(200),
        child: Column(
          children: <Widget>[
            GestureDetector(
                onTap: () {
                  getPic();
                },
                child: Container(
                  child: Text("拍照"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                )),
            Container(
              height: AppSize.height(1),
              width: double.infinity,
              color: Colours.color_dcdcdc,
            ),
            GestureDetector(
                onTap: () {
                  getLocalPic();
                },
                child: Container(
                  child: Text("相册"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                ))
          ],
        ));
  }

  //选择照片
  Widget _showImageTip(BuildContext context) {
    return new Container(
        height: AppSize.height(200),
        child: Column(
          children: <Widget>[
            GestureDetector(
                onTap: () {
                  getCameraPic();
                },
                child: Container(
                  child: Text("拍照"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                )),
            Container(
              height: AppSize.height(1),
              width: double.infinity,
              color: Colours.color_dcdcdc,
            ),
            GestureDetector(
                onTap: () {
                  getLocalSelectPic();
                },
                child: Container(
                  child: Text("相册"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                ))
          ],
        ));
  }

  Future getPic() async {
    PickedFile image = await _picker.getImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
    Navigator.of(context).pop();
    String fileName = image.path
        .substring(image.path.lastIndexOf('/') + 1, image.path.length)
        .toString();
    String ext = image.path
        .substring(image.path.lastIndexOf('.') + 1, image.path.length)
        .toString();
    Base64Tool.imageBase64(image.path).then((base64Str) {
      ApiInterface.uploadPublicImage(base64Str, ext, fileName).then((data) {
        //上传图片成功处理
        cardentity =
            UploadImageResponseEntity().fromJson(data);
      });
    });
  }

  Future getCameraPic() async {
    PickedFile image = await _picker.getImage(source: ImageSource.camera);
    Navigator.of(context).pop();
    String fileName = image.path
        .substring(image.path.lastIndexOf('/') + 1, image.path.length)
        .toString();
    String ext = image.path
        .substring(image.path.lastIndexOf('.') + 1, image.path.length)
        .toString();
    Base64Tool.imageBase64(image.path).then((base64Str) {
      ApiInterface.uploadPublicImage(base64Str, ext, fileName).then((data) {
        //上传图片成功处理
        if (image != null) {
          setState(() {
            _imageBackCard = File(image.path);
          });
        }
        cardentity =
            UploadImageResponseEntity().fromJson(data);
      });
    });
  }


  Future getLocalPic() async {
    PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    Navigator.of(context).pop();
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
    String fileName = image.path
        .substring(image.path.lastIndexOf('/') + 1, image.path.length)
        .toString();
    String ext = image.path
        .substring(image.path.lastIndexOf('.') + 1, image.path.length)
        .toString();
    Base64Tool.imageBase64(image.path).then((base64Str) {
      LoadingUtil.showLoading(context, tip: '加载中...');
      ApiInterface.uploadPublicImage(base64Str, ext, fileName).then((data) {
        //上传图片成功处理
        backcardentity = UploadImageResponseEntity().fromJson(data);
      }).catchError((onError) {
        setState(() {
          //上传失败进行清除
          _image = null;
        });
      }).whenComplete(() => LoadingUtil.hideLoading(context));
    });
  }

  Future getLocalSelectPic() async {
    Navigator.of(context).pop();
    PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _imageBackCard = File(image.path);
      });
    }
    String fileName = image.path
        .substring(image.path.lastIndexOf('/') + 1, image.path.length)
        .toString();
    String ext = image.path
        .substring(image.path.lastIndexOf('.') + 1, image.path.length)
        .toString();
    Base64Tool.imageBase64(image.path).then((base64Str) {
      uploadImage(base64Str, ext, fileName);
    });
  }

  void uploadImage(String files, String ext, String fileName) async {
    ApiInterface.uploadPublicImage(files, ext, fileName)
        .then((data) {
      backcardentity = UploadImageResponseEntity().fromJson(data);
    }).catchError((onError) {
      setState(() {});
      _imageBackCard = null;
    });
  }

  Image getImage() {
    if(cardentity != null && cardentity.content != null && cardentity.content.length >0){
      return (cardentity.content[0].path != null && cardentity.content[0].path.length > 0)? Image.network(cardentity.content[0].path, width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,): (_image != null
          ? Image.file(
        _image,
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      )
          : Image.asset(
        'images/mine_frontIDcard.png',
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      ));
    }else{
      return _image != null
          ? Image.file(
        _image,
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      )
          : Image.asset(
        'images/mine_frontIDcard.png',
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      );
    }

  }

  Image getBackCardImage() {

    if(backcardentity != null && backcardentity.content != null && backcardentity.content.length >0){
      return (backcardentity.content[0].path != null && backcardentity.content[0].path.length > 0)? Image.network(backcardentity.content[0].path, width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,): (_imageBackCard != null
          ? Image.file(
        _imageBackCard,
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      ) : Image.asset(
        'images/mine_reverseIDcard.png',
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      ));
    }else{
      return _imageBackCard != null
          ? Image.file(
        _imageBackCard,
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      ) : Image.asset(
        'images/mine_reverseIDcard.png',
        width: AppSize.width(308),
        height: AppSize.height(168),
        fit: BoxFit.cover,
      );
    }
  }

  void _save() {
    //输入验证判断
    if (_relNameeditingController.text.length <= 0) {
      showToast('请输入正确的真实姓名');
      return;
    }

    if (selectMarketId == 0) {
      showToast('请选择经营类型');
      return;
    }

    bool isAvailable = isCardId(_carNumbereditingController.text);
    if (!isAvailable && _carNumbereditingController.text.length > 0) {
      showToast('请输入正确的身份证号码');
      return;
    }

    if (!this.isSelectButton) {
      showToast("请勾选并同意告知书");
      return;
    }

    Map<String, dynamic> parameter = new Map();
    parameter['name'] = _relNameeditingController.text;
    parameter['type'] = this.recordType;
    parameter['businessTypeId'] = selectMarketId;
    if(informationEntity.id > 0) {
      parameter['id'] = informationEntity.id;
    }
    parameter['phone'] = Global.prefs.getString(Global.phone);

    if (_carNumbereditingController.text.length > 0) {
      parameter['idCardNo'] = _carNumbereditingController.text;
    }
    if(cardentity != null && cardentity.content.length > 0 && cardentity.content[0].path.length > 0){//正面照片
      parameter['fileIdi'] = cardentity.content[0].id;
      parameter['filePathi'] = cardentity.content[0].path;
    }
    if(backcardentity != null && backcardentity.content.length > 0 && backcardentity.content[0].path.length > 0){//反面照片
      parameter['fileIdii'] = backcardentity.content[0].id;
      parameter['filePathii'] = backcardentity.content[0].path;
    }

    LoadingUtil.showLoading(context, tip: '正在保存，请稍后');
    ApiInterface.personInformationSave(parameter).then((data) {
      LoadingUtil.hideLoading(context);
      PersoninformationResponseEntity entity = PersoninformationResponseEntity().fromJson(data);
      //存储consumerId
      Global.prefs.setString(Global.consumer_id, entity.account.consumerId.toString());
      if (widget.type == 1) {
        Navigator.pop(context);
      } else {
        //跳转到首页
        Navigator.pushNamedAndRemoveUntil(context, home_page, (route) => false);
      }
    }).catchError((error) {
      LoadingUtil.hideLoading(context);
    });
  }
}
